/*
** server.c for  in /home/jousse_f//workspace/SysUnix/ftp
** 
** Made by florian jousseau
** Login   <jousse_f@epitech.net>
** 
** Started on  Mon Apr  2 16:38:01 2012 florian jousseau
** Last update Wed Apr  4 15:48:15 2012 florian jousseau
*/

#include "client.h"

t_cmd	tab0[] =
  {
    {"ls", 1},
    {"pwd", 1},
    {"quit", 2},
    {"cd", 1},
    {"z", 0}
  };

t_cmd	tab1[] =
  {
    {"cd ", 1},
    {"get ", 1},
    {"put ", 1},
    {"z", 0}
  };

int	check_command(char buf[512])
{
  int		i;
  int		ret;

  ret = 0;
  i = 0;
  while (strncmp(buf, tab1[i].str, strlen(tab1[i].str)) != 0 &&
	 strcmp(tab1[i].str, "z") != 0)
    i++;
  ret = tab1[i].i;
  if (strcmp(tab1[i].str, "z") == 0)
    {
      i = 0;
      while (strcmp(buf, tab0[i].str) != 0 &&
	     strcmp(tab0[i].str, "z") != 0)
	i++;
      ret = tab0[i].i;
    }
  return (ret);
}

void	do_client(struct sockaddr_in	sin, int s)
{
  char			*buf;
  int			len;
  int			cont;

  cont = 0;
  buf = malloc(sizeof(char) * 512);
  printf("Connected to %s\n", inet_ntoa(sin.sin_addr));
  read(s, buf, 512);
  printf("%s\n", buf);
  while (cont == 0)
    {
      write(1, "FTP > ", 6);
      len = read(0, buf, 512);
      buf[len - 1] = '\0';
      if (check_command(buf) != 0)
	write(s, buf, strlen(buf));
      if (check_command(buf) == 2)
	cont = 1;
      if (check_command(buf) != 0 && read(s, buf, 512) <= 0)
      	cont = 1;
    }
}

int		main(int ac, char **av)
{
  struct protoent	*pe;
  struct sockaddr_in	sin;
  int			s;
  int			port;
  int			error;

  if (ac != 3)
    exit(EXIT_FAILURE);
  port = atoi(av[2]);
  pe = getprotobyname("TCP");
  s = socket(AF_INET, SOCK_STREAM, pe->p_proto);
  if (s == -1)
    {
      printf("socket\n");
      exit(EXIT_FAILURE);
    }
  sin.sin_family = AF_INET;
  sin.sin_port = htons(port);
  sin.sin_addr.s_addr = inet_addr(av[1]);
  error = connect(s, (const struct sockaddr *)&sin, sizeof(sin));
  if (error == -1)
    {
      printf("Cannot not connect to server\n");
      close(s);
      exit(EXIT_FAILURE);
    }
  do_client(sin, s);
  close(s);
  return (EXIT_SUCCESS);
}
